# =============================================================================================
# - THIS FILE REPLICATES TABLES 6--8
# =============================================================================================

# =============================================================================================
# LOAD DATA
# =============================================================================================

# load packages
library(data.table); library(magrittr); library(fastmatch); library(pbapply); library(xts)
library(timeDate); library(bizdays); library(fasttime)
library(xtable); library(stargazer); library(haven); library(lfe)
library(ggplot2); library(cowplot); library(grid); library(ggridges)
library(bife); library(scales);library(texreg); library(alpaca)

# color-blind palette
cbp <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7",
         "#888888")
bdf_pale <- rgb(0.192, 0.549, 0.906, alpha = 0.35)
bdf <- rgb(0.192, 0.549, 0.906, alpha = 1)

# set locale
Sys.setlocale(locale = 'US')

# load user-defined function
source('desc.R')

load_rmetrics_calendars(seq(2002, 2023, 1))

# load
load(file = 'replica_cdeb.RData')
load(file = 'replica_cmtn.RData')

# =============================================================================================
# TABLE 8
# =============================================================================================

sub_event_df[, itm_mkt_pre_reg := factor(itm_mkt_pre, levels = c('ITM', 'ATM', 'OTM'))]
sub_event_df_cmtn[, itm_mkt_pre_reg := factor(itm_mkt_pre, levels = c('ITM', 'ATM', 'OTM'))]

m <- vector('list', 8)

m[[1]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre
               |year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df)

m[[2]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre+
               dts+ret_equity+dnetvlm|year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df)

m[[3]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre
               |year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df[per=='postgfc'])

m[[4]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre+
                 dts+ret_equity+dnetvlm|year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df[per=='postgfc'])

m[[5]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre
               |year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df_cmtn)

m[[6]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre+
                 dts+ret_equity+dnetvlm|year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df_cmtn)

m[[7]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre
               |year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df_cmtn[per=='postgfc'])

m[[8]] <- felm(xsret ~ itm_mkt_pre_reg+ surprise_dummy:itm_mkt_pre_reg+size_hist_pre+mat_pre+coupon_pre+
                 dts+ret_equity+dnetvlm|year+issuer+rating_num_pre|0|issuer, cmethod = 'reghdfe', 
               data = sub_event_df_cmtn[per=='postgfc'])

mod <- capture.output(
      
      stargazer(out = paste0('T8.tex'),
                m,
                font.size = "footnotesize", no.space = T, omit.stat = c('ser', 'rsq'),
                covariate.labels = c('$\\mathbb{1}^{\\text{Surprise}}\\times\\mathbb{1}^{\\text{ITM}}$',
                                     '$\\mathbb{1}^{\\text{Surprise}}\\times\\mathbb{1}^{\\text{ATM}}$',
                                     '$\\mathbb{1}^{\\text{Surprise}}\\times\\mathbb{1}^{\\text{OTM}}$',
                                     'Return volatility',
                                     'Equity return',
                                     '$\\Delta ADNV$',
                                     '$\\mathbb{1}^{\\text{ATM}}$',
                                     '$\\mathbb{1}^{\\text{OTM}}$'),
                float = F, intercept.top = T, intercept.bottom = F, digits = 2,
                omit = c('size_hist_pre', 'mat_pre', 'coupon_pre'),
                column.labels = c('Corporate Debentures', 'Corporate MTN'),
                column.separate = c(4,4),
                model.numbers = T, model.names = F,
                dep.var.caption = "$\\text{Dependent variable:~}XR$",
                dep.var.labels.include = F,
                order = c(':',
                          'dts',
                          'ret_equity',
                          'dnetvlm',
                          '^itm_mkt_pre_regITM$',
                          '^itm_mkt_pre_regATM$',
                          '^itm_mkt_pre_regOTM$'),
                add.lines = list(c("Sample", c(rep('Full', 2), rep('2010+', 2), rep('Full', 2), rep('2010+', 2))),
                                 c("Bond controls", rep('YES',8)),
                                 c("Year, Issuer FEs", rep('YES', 8))),
                notes.align = 'l', column.sep.width = "0pt")
      
    )
    
mod <- sub("lcccccccc", "lcccc|cccc", mod)
    
writeLines(mod, paste0('T8.tex'))

# =============================================================================================
# TABLE 7
# =============================================================================================

m = vector('list')
sub_event_df[, called := as.numeric(event_call)*100]
sub_event_df[, calliv_mkt_pre_itm := calliv_mkt_pre*as.numeric(itm_mkt_pre%in%c('ATM', 'ITM'))]

extradf <- sub_event_df[, .(issuer, cusip_id, year, issuerxyear, event_date, called, xsret,
                            event_call, calliv_mkt_pre, dts, busy, cash_pre,
                            size_hist_pre, rating_num_pre, mat_pre, rating, ret_equity, ret_equity_prior,
                            mve_bln_pre, bl1_pre, bl2_pre, ml_pre, atan_pre, pm_pre, tpr_pre, capexr_pre)]
colstosd <- c('calliv_mkt_pre', 'dts',
              'size_hist_pre', 'mat_pre', 'ret_equity', 'ret_equity_prior',
              'mve_bln_pre', 'bl1_pre', 'bl2_pre', 'ml_pre', 'atan_pre', 'pm_pre', 'tpr_pre', 'capexr_pre')

extradf[, (colstosd) := lapply(.SD, function(x){x/sd(x, na.rm = T)}), .SDcols = colstosd]
extradf[, HY := 0]
extradf[rating_num_pre > 10, HY := 1]

setkey(extradf, issuer, event_date)
extradf[, nbevent := seq(1, .N, 1), .(issuer, cusip_id)]
extradf[, (paste0('lag_', 1:2, '_IV')) := shift(calliv_mkt_pre, n = 1:2, type = 'lag'), .(cusip_id)]
extradf[!is.na(lag_1_IV), ivup := 0]
extradf[calliv_mkt_pre - lag_1_IV > 0, ivup := 1]

m[[1]] <- glm(event_call ~ calliv_mkt_pre + dts,
                data=extradf, family = binomial('logit'))

m[[2]] <- feglm(event_call ~ calliv_mkt_pre + dts|year|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[3]] <- feglm(event_call ~ calliv_mkt_pre + dts|year+rating_num_pre|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[4]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre|year+rating_num_pre|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[5]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre+
                       mve_bln_pre + bl1_pre |year+rating_num_pre|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[6]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre+
                       mve_bln_pre + ml_pre |year+rating_num_pre|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[7]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre+
                       mve_bln_pre + bl1_pre + pm_pre + tpr_pre + cash_pre|year+rating_num_pre|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[8]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre+
                       mve_bln_pre + bl1_pre + pm_pre + tpr_pre + cash_pre|year+rating_num_pre+issuer|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

m[[9]] <- feglm(event_call ~ calliv_mkt_pre + dts +size_hist_pre+mat_pre+
                  mve_bln_pre + bl1_pre + pm_pre + tpr_pre + cash_pre +
                  + busy|year+rating_num_pre+issuer|issuer,
                data=extradf, family = binomial('logit'), control = list(drop.pc = F))

# extract ribust SEs and PVs
sel <- list('SE' = vector(mode = 'list', length = length(m)),
            'PV' = vector(mode = 'list', length = length(m)))

for (i in 1:length(m)) {
  
  if (i %in% c(2:9)) {
    
    A <- summary(m[[i]], type = 'clustered', cluster = ~ year)$cm
    
  } else {
   
    A <- summary(m[[1]])$coefficients
     
  }
 
  sel$SE[[i]] <- as.numeric(A[,2])
  sel$PV[[i]] <- as.numeric(A[,4])
   
}

texreg(file = 'T7.tex',
       l = m,
       custom.header = list("Dependent variable: $\\mathbf{P}_i\\left[\\text{Called}\\right]$" = 1:length(m)),
       custom.model.names = paste0('(',1:length(m),")"),
       custom.coef.names = c('Intercept', 'Intrinsic value (IV)',
                             'Return volatility',
                             'Outstanding amount', 'Maturity',
                             'Equity value', 'Book leverage', 'Market leverage',
                             'Profit margin', 'Total payout ratio', 'Cash ratio',
                             'Fiscal year-end (dummy)'),
       override.se = sel$SE,
       override.pvalues = sel$PV,
       include.deviance = F,
       include.aic = F,
       include.bic = F,
       include.loglik = F,
       include.groups = F,
       stars = c(0.01, 0.05, 0.1),
       table = F,
       custom.gof.rows = list("Year FE" = c('NO', rep('YES',8)),
                              "Rating FE" = c(rep('NO', 2), rep('YES',7)),
                              "Issuer FE" = c(rep('NO', 7), 'YES', 'YES'))
)

# =============================================================================================
# TABLE 6a
# =============================================================================================

# Nobs by money-ness and call decision
tab <- as.data.frame(dcast(sub_event_df, 'event_call ~ itm_mkt_pre')[,-1])
tab[3,] <- tab[2,]/(tab[1,]+tab[2,])*100
tab[4,] <- tab[1,]+tab[2,]

tab2 <- as.data.frame(dcast(sub_event_df[gfc==F], 'event_call ~ itm_mkt_pre')[,-1])
tab2[3,] <- tab2[2,]/(tab2[1,]+tab2[2,])*100
tab2[4,] <- tab2[1,]+tab2[2,]

tab3 <- as.data.frame(dcast(sub_event_df[postgfc==T], 'event_call ~ itm_mkt_pre')[,-1])
tab3[3,] <- tab3[2,]/(tab3[1,]+tab3[2,])*100
tab3[4,] <- tab3[1,]+tab3[2,]

tab <- cbind(tab, tab3)
remove(tab2, tab3)
tab <- rbind(tab[4,], tab[1:3,])

rownames(tab) <- c('No. bond-events', '~~no. no-calls', '~~no. calls', '~~\\% called')

addtorow = list()
addtorow$pos = list(-1, nrow(tab))
addtorow$command = c("\\hline \\hline  & \\multicolumn{3}{c|}{Full sample} & \\multicolumn{3}{c}{Post-GFC} \\\\\n",
                     "\\hline")

digimat <- matrix(0, nrow = nrow(tab), ncol = ncol(tab)+1)
digimat[4,] <- 1

print(xtable(tab, auto = F,
             align = 'l|ccc|ccc',
             digits = digimat),
      file = 'T6a.tex', floating = F,
      include.colnames = T,
      include.rownames = T, size = 'footnotesize', sanitize.text.function=function(x){x},
      hline.after = c(0,nrow(tab)), add.to.row = addtorow)

# =============================================================================================
# TABLE 6b
# =============================================================================================

# Nobs by money-ness and call decision
tab <- as.data.frame(dcast(sub_event_df_cmtn, 'event_call ~ itm_mkt_pre')[,-1])
tab[3,] <- tab[2,]/(tab[1,]+tab[2,])*100
tab[4,] <- tab[1,]+tab[2,]

tab2 <- as.data.frame(dcast(sub_event_df_cmtn[gfc==F], 'event_call ~ itm_mkt_pre')[,-1])
tab2[3,] <- tab2[2,]/(tab2[1,]+tab2[2,])*100
tab2[4,] <- tab2[1,]+tab2[2,]

tab3 <- as.data.frame(dcast(sub_event_df_cmtn[postgfc==T], 'event_call ~ itm_mkt_pre')[,-1])
tab3[3,] <- tab3[2,]/(tab3[1,]+tab3[2,])*100
tab3[4,] <- tab3[1,]+tab3[2,]

tab <- cbind(tab, tab3)
remove(tab2, tab3)
tab <- rbind(tab[4,], tab[1:3,])

rownames(tab) <- c('No. bond-events', '~~no. no-calls', '~~no. calls', '~~\\% called')

addtorow = list()
addtorow$pos = list(-1, nrow(tab))
addtorow$command = c("\\hline \\hline  & \\multicolumn{3}{c|}{Full sample} & \\multicolumn{3}{c}{Post-GFC} \\\\\n",
                     "\\hline")

digimat <- matrix(0, nrow = nrow(tab), ncol = ncol(tab)+1)
digimat[4,] <- 1

print(xtable(tab, auto = F,
             align = 'l|ccc|ccc',
             digits = digimat),
      file = 'T6b.tex', floating = F,
      include.colnames = T,
      include.rownames = T, size = 'footnotesize', sanitize.text.function=function(x){x},
      hline.after = c(0,nrow(tab)), add.to.row = addtorow)